<?

class Sessions extends MY_Controller {

    function Sessions() {

        parent::MY_Controller();

    }

    function index() {

        redirect('sessions/login');

    }

    function login() {

        if ($this->mdl_sessions->validate_login()) {

            if ($user = $this->mdl_auth->auth('inktype_users', 'email_address', 'password', $this->input->post('email_address'), $this->input->post('password'))) {

                $this->session->sess_destroy();

                // check to see if any meta updates need to be made since this user's last login
                $this->mdl_users->meta_update($user->user_id);

                // retrieve the meta keys and values
                $meta = $this->mdl_users->get_meta($user->user_id);

                // get the user's primary site
                if ($user->user_type_id == 1 or $user->user_type_id == 3) {

                // this is a global user, so assign the 'default' site id
                    $this->db->where('is_default', 1);

                    $query = $this->db->get('inktype_sites');

                    $default_site = $query->row();

                    $user->site_id = $default_site->site_id;

                }

                else {

                // this is a local user, so assign to assigned site
                    $user->site_id = $user->site_id;

                }

                $user->current_site_url = $this->inktype_system->current_site_url($user->site_id);

                $object_vars = array('user_id', 'display_name', 'user_type_id', 'email_address', 'last_login', 'current_site_url', 'site_id');

                // set the session variables
                $this->mdl_auth->set_session($user, $object_vars, $meta);

                // update the last login field for this user
                $this->mdl_auth->update_timestamp('inktype_users', 'user_id', $user->user_id, 'last_login', time());

                if ($this->mdl_user_types->is_admin($user->user_type_id)) {

                    redirect('admin_index');

                }

                else {

                    redirect($user->current_site_url);

                }

            }

            else {

                $this->validation->error_string = TRUE;

            }

        }

        $this->load->view('admin/login');

    }

    function logout() {

        $this->session->sess_destroy();

        redirect('sessions/login');

    }

}

?>